#include <iostream>
using namespace std;

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string>
#include <cstring>

#define BUFFER_SIZE 64

void cp(const string& text1,const string& text2)
{
    const char * filename1 = "./text1";
    int fd1 = open(filename1,O_RDWR | O_CREAT,0644);

    const char * filename2 = "./text2";
    int fd2 = open(filename2,O_RDWR | O_CREAT,0644);

    char buffer[BUFFER_SIZE] = {0};
    ssize_t bytesRead;
    while((bytesRead = read(fd1, buffer, sizeof(buffer) - 1)) > 0)
    {
        //清除脏数据
        bzero(buffer,sizeof(buffer));
        read(fd1,buffer,sizeof(buffer)-1);
        lseek(fd1, 1024, SEEK_SET);
        write(fd2,buffer,BUFFER_SIZE-1);
        lseek(fd2,0,SEEK_END);
    }

    close(fd1);
    close(fd2);
}

int myCopyFile(const char * dest,const char *src)
{
    int fd1 = open(src,O_RDONLY);
    if(fd1 == -1)
    {
        printf("src file not exist.\n");
        return -1;
    }

    int permission = 0;
    access(src,W_OK) == 0 ? permission |= W_OK:permission;
    access(src,R_OK) == 0 ? permission |= R_OK:permission;
    access(src,X_OK) == 0 ? permission |= X_OK:permission;
    int fd2 = open(dest,O_WRONLY | O_CREAT | O_TRUNC,permission);
    if(fd2  == -1)
    {
        perror("dest file error:");
        return -1;
    }

    char buffer[BUFFER_SIZE] = {0};

    while(1)
    {
        size_t readBytes = read(fd1,buffer,sizeof(buffer)-1);
        if(readBytes <= 0)
        {
            break;
        }
        write(fd2,buffer,readBytes);
    }
    close (fd1);
    close (fd2);

    return 0;
}
    


//命令行参数
int main(int argc,const char *argv[])
{   
    //命令行参数的个数
    if(argc != 3)
    {
        printf("input arguments too few.\n");
        return -1;
    }
    // cout<<"argc:"<<argc<<endl;

    const char * srcFile = argv[1];
    const char * dstFile = argv[2];
    // for(int idx = 0; idx < argc;idx++)
    // {
    //     printf("argv[%d] = %s\n",idx,argv[idx]);
    // }
    myCopyFile(dstFile,srcFile);
    return 0;
}